import axios from 'axios'
import { Message } from 'element-ui';
import { getTime } from '@/utils/auth'
import store from '@/store';

//cookie过期时间
let cookieout = 3600

const request = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,//基础地址
    timeout: 5000
})

request.interceptors.request.use(function (config) {
    //cookie是否过期
    if (cookieTimeOut(getTime())) {
        store.dispatch('user/logout')
        Message.error('自动登陆身份已过期,请重新登陆!')
        return Promise.reject(new Error())
    }

    // 在发送请求之前做些什么
    if (store.getters.token) {
        config.headers['Authorization'] = 'Bearer ' + store.getters.token
    }
    return config;
})

//响应拦截设置
request.interceptors.response.use(response => {
    let { data, success, message } = response.data
    // console.log(response.data)
    if (success) {
        return data
    } else {
        Message.error(message)
        return Promise.reject(new Error(message))
    }

}, error => {
    if (error.response && error.response.data && error.response.data.code) {
        store.dispatch('user/logout')
        Message.error('身份已过期,请重新登陆!')
        return Promise.reject(error)
    }
    Message.error(error)
    return Promise.reject(error)
})

//判断cookie是否过期
function cookieTimeOut(date) {
    let currentTime = new Date()
    return (currentTime - new Date(date)) / 1000 > cookieout
}

export default request
